//
//  NearbyUser.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

class NearbyUser: UIViewController,UITableViewDelegate, UITableViewDataSource, HttpProtocol{
    
    var Users = [NearbyUserModel]()
    var tableData:[JSON]=[]
    
    var StreetNameStr:String?
    
    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    
    var eHttp:HTTPController = HTTPController()
    
    @IBOutlet weak var AllUserList: UITableView!
    
    @IBAction func AddFriendAction(sender: AnyObject) {
        //添加好友功能
        //print(sender.tag)
        //let cell = sender.superview!!.superview
        let view:UIView! = sender.superview
        let cell:UITableViewCell! = view.superview as! UITableViewCell
        
        let index = self.AllUserList.indexPathForCell(cell)
        print(index?.row)
        let indexrow = index!.row
        //添加好友请求
        var parameters = [
            "user1": keychain.get("registerUserID")!,
            "user2": Users[indexrow].UserIDStr
        ]
        
        let BaseUrl = "http://42.62.18.210:8090/apiradio/ar/addFriend"
        Alamofire.request(.POST, BaseUrl, parameters:parameters).responseJSON { response in
            if let result = response.result.value {
                print(result)
                let json = JSON(result)
                if(json["msg"] == "200") {
                    //添加好友成功
                    //1.先对这个cell进行删除
                    self.Users.removeAtIndex(indexrow)
                    self.AllUserList.deleteRowsAtIndexPaths([index!], withRowAnimation: UITableViewRowAnimation.Automatic)
                    
                    //在这里修改
                    
                    //2.弹出框显示成功
                    var alert = UIAlertView()
                    alert.title = "提示"
                    alert.message = "添加好友成功"
                    //alert.addButtonWithTitle("Cancel")
                    alert.addButtonWithTitle("OK")
                    alert.show()
                }
                
                
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = StreetNameStr!
        print(StreetNameStr)
        
        //请求街道的所有用户
        eHttp.delegate = self
        
        AllUserList.delegate = self
        AllUserList.dataSource = self
        
        var parameters = [
            "userID":keychain.get("registerUserID")!,
            "lng":keychain.get("registerlongitude")!,
            "lat":keychain.get("registerlatitude")!,
            "street": StreetNameStr!,
            "page": "1"
        ]
        
        let BaseUrl = "http://42.62.18.210:8090/apiradio/ar/getUsersByStreet"
        Alamofire.request(.GET, BaseUrl, parameters:parameters).responseJSON { response in
            if let result = response.result.value {
                let json = JSON(result)
                if let channels = json["obj"].array {
                    print(channels)
                    
                    self.tableData = channels
                    
                    for var i = 0; i < self.tableData.count; i++
                    {
                        let rowData:JSON = self.tableData[i]
                        // print(rowData["channelName"].string)
          
                       // self.Users.append(NearbyUserModel(PlateNum: String(rowData["plateNumber"]), PortailHeader: String(rowData["headerPath"]), Distance: String(rowData["distance"]), UserSex: String(rowData["sex"])))
                        self.Users.append(NearbyUserModel(personTopic: String(rowData["personTopic"]), UserID: String(rowData["userID"]), PlateNum: String(rowData["plateNumber"]), PortailHeader: String(rowData["headerPath"]), Distance: String(rowData["distance"]), UserSex: String(rowData["sex"])))

                        
                    }
                    
                    self.AllUserList!.reloadData()
                }
                
                
            }
        }
        
        
        
        //eHttp.onsearch(getUserUrl)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "UserListCell"
        
        var cell: NearbyUserModelList! = tableView.dequeueReusableCellWithIdentifier(identifier) as? NearbyUserModelList
        
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        //cell.tag = indexPath.row
        if cell == nil {
            cell = NearbyUserModelList(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(Users[indexPath.row])
        
        return cell!
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.Users.count
    }
    
    /* 获取街道数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        print("results: \(results)")
    }
        
    
}
